package com.yfeng.goodjuhome.service.impl;

import com.yfeng.exception.DownloadException;
import com.yfeng.exception.HomeRuntimeException;
import com.yfeng.exception.UploadException;

import com.yfeng.goodjuhome.service.IFileService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service("fileService")
public class FileServiceImpl  implements IFileService {
	//存放文件的跟目录
	private String diskDir=null;
	private final Log logger = LogFactory.getLog(this.getClass());

	public String getDiskDir() {
		return diskDir;
	}

	public void setDiskDir(String diskDir) {
		this.diskDir = diskDir;
	}

	public InputStream downloadFile(String fileID, String pageCount) throws DownloadException {
		//根据fileID 查询到文件filePaht
		String filePaht="";
		File file=new File(filePaht);
		File[] files = file.listFiles();
		InputStream in=null;
		for (int i = 0; i < files.length; i++) {
			File tempfile = files[i];
			if (StringUtils.substringBeforeLast(tempfile.getName(), ".").equals(pageCount)) {
				try {
					 in = new FileInputStream(tempfile);
				} catch (FileNotFoundException e) {
					throw new DownloadException(e.getMessage(),e);
				}
				break;
			}
		}
		return in;
	}

	public String uploadFile(HashMap<String, String> formMap,
			List<FileItem> filelist) throws UploadException {
		String descPath=this.getUrl();
		for(FileItem item:filelist){
			this.saveFile(item, descPath);
		}
		//写数据库返回fileID
		return null;
	}


	/**
	 * 根据规则生成 url
	 * */
	private String getUrl() {
		// 当前时间 格式如：2009/04/20/08/30/45
		Date current_time = new Date();
		Random rand = new Random();
		int i = rand.nextInt(10000);
		i = Math.abs(i);
		// 位数不够需要补0
		NumberFormat formatter = NumberFormat.getNumberInstance();
		formatter.setMinimumIntegerDigits(5);
		formatter.setGroupingUsed(false);
		 String s = formatter.format(i);
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss/SSS");
		String str_sysdate = df.format(current_time);
		String url = "/" + str_sysdate+s;
		return url;
	}


	/**
	 * 保存文件
	 *
	 * @param item
	 * @param descPath
	 * @throws UploadException
	 */
	private void saveFile(FileItem item, String descPath) throws UploadException
			 {
		File fi = new File(descPath);
		try {
			File pf = fi.getParentFile();
			if (!pf.exists()) {
				boolean b = pf.mkdirs();
				if (!b) {
				boolean c=this.makeDirs(pf.getPath());
					if(!c){
						this.makeDirs(pf.getPath());
					}
				}
			}
			item.write(fi);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new UploadException("saveFile error:"+e.getMessage(),e);
		} finally{
			if(item!=null){
				try {
					item.getInputStream().close();
				} catch (IOException e) {
					//此异常不处理
				}
				try{
					item.delete();
				}catch (Exception e) {
					//此异常不处理
				}
			}
		}
	}



	/**
	 * 删除文件
	 */
	private void deleteFile(String fileID) {
		File fi = null;
		String filePath="";
		try {
			fi = new File(this.getDiskDir()+filePath);
			File[] filelist = fi.listFiles();
			for (int i = 0; (filelist != null) && (i < filelist.length); i++) {
				if (filelist[i].isDirectory()) {
					return;
				}
			}
			FileUtils.cleanDirectory(fi);
		} catch (FileNotFoundException e) {
			//删除文件异常不处理
		} catch (IOException e) {
			//删除文件异常不处理
		}

	}

	/**
	 * 创建文件夹
	 * */
	private  boolean makeDirs(String dir)
	{
		String[] dirs = dir.split("/");
		StringBuffer newDir = new StringBuffer("/");
		if (dirs == null || dirs.length == 0){

			return false;
		}
		for (int i = 0; i < dirs.length; i++)
		{
			newDir.append(dirs[i]);
			File newFile = new File(newDir.toString());
			if (!newFile.exists()) {
				if (!newFile.mkdir()) {
					if(!newFile.exists()){
						return false;
					}
				}
			}
			newDir.append("/");
			continue;
		}
		return true;
	}

	
	public void afterPropertiesSet() throws Exception {
		if(this.getDiskDir()==null){
			throw new HomeRuntimeException("请设置存放文件的跟目录！");
		}
	}

}
